package com.jab.controller;

import com.jab.pojo.Img;
import com.jab.service.FileUploadService;
import com.jab.service.ImgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @PackgeName: com.jab.controller
 * @ClassName: FileUploadController
 * @Author: 零
 * Date: 2022/3/31 14:19
 * project name: osstest
 * @Version:
 * @Description:
 */
@RequestMapping("new")
@RestController
@CrossOrigin
public class FileUploadController {

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    private ImgService imgService;

    /*
     * 文件上传api
     */
    @PostMapping("upload")
    public Map<String,Object> upload(@RequestParam("file") MultipartFile file) {
        Map<String,Object> map = new HashMap<>();
        Img img = new Img();
        if (file != null) {
            String returnFileUrl = fileUploadService.upload(file);
            if (returnFileUrl.equals("error")) {
                map.put("error", "文件上传失败！");
                return map;
            }
            img.setUrl(returnFileUrl);
            imgService.save(img);
            map.put("success", "文件上传成功！");
            System.out.println(returnFileUrl);

            map.put("returnFileUrl", returnFileUrl);
            return map;
        } else {
            map.put("error", "文件上传失败！");
            return map;
        }
    }

    @RequestMapping("query")
    public List<Img> query(){
        return imgService.list();
    }
}
